<?php


namespace app\shop\service\chat;


use app\shop\common\consts\Consts;
use app\shop\common\consts\RedisKey;
use app\shop\model\chat\GroupUserModel;
use app\shop\model\file\FileModel;
use app\shop\model\order\OrderModel;
use app\shop\model\user\ChatUserModel;
use app\shop\model\user\MessageModel;
use app\shop\model\user\UserModel;
use app\shop\service\until\FileService;
use GatewayClient\Gateway;
use think\facade\Cache;

class ChatService
{

    public static function getSendData($chatSign, $fromUserInfo, $content, $type = 'text', $fileId = 0, $orderId = 0, $id = '')
    {

        if ($fileId > 0) {
            $fileInfo = FileModel::find($fileId);
            $fileName = $fileInfo['name'] ?? '';
            $fileSize = $fileInfo['size'] ?? 0;
        } else {
            $fileName = '';
            $fileSize = 0;
        }
        $fromUserInfo['id'] = $fromUserInfo['user_id'];
        $data = [
            'at' => [],
            'content' => $content,
            'extends' => [],
            'fileName' => $fileName,
            'fileSize' => $fileSize,
            'file_cate' => 0,
            'file_id' => $fileId,
            'from_user' => $fromUserInfo,
            'fromUser' => $fromUserInfo,
            'id' => $id ?: generateUuidV4(),
            'is_read' => 0,
            'msg_id' => 0,
            'orderId' => $orderId,
            'sendTime' => intval(time() * 1000),
            'sensitive_word_id' => 0,
            'status' => 'succeed',
            'type' => $type,
            'chat_sign' => $chatSign,
            'auto_reply' => 0,
        ];
        return $data;
    }

    /**
     * 写入表的信息
     * @param $chatSign
     * @param $fromUserInfo
     * @param $content
     * @param $msgType
     * @param string $id
     * @param int $fileId
     * @param string $quote
     * @param null $extends
     * @param  $orderId
     * @return array
     * @throws \Exception
     */
    public static function getMessageData($chatSign, $fromUserInfo, $content, $msgType, $id = '', $fileId = 0, $quote = '', $extends = null, $orderId = 0)
    {
        try {
            if ($fileId > 0) {
                $fileInfo = FileModel::find($fileId);
                $fileName = $fileInfo['name'] ?? '';
                $fileSize = $fileInfo['size'] ?? 0;
                $fileCate = $fileInfo['cate'] ?? 0;
            } else {
                $fileName = '';
                $fileSize = 0;
                $fileCate = 0;
            }
            $data = [
                'from_user' => $fromUserInfo['user_id'],
                'from_user_role_id' => $fromUserInfo['role_id'],
                'chat_sign' => $chatSign,
                'id' => $id ?: generateUuidV4(),
                'content' => str_encipher($content, true),
                'create_time' => time(),
                'type' => $msgType,
                'is_group' => 1,
                'is_read' => 0,
                'file_id' => $fileId,
                "file_cate" => $fileCate,
                'file_size' => $fileSize,
                'file_name' => $fileName,
                'at' => [],
                'quote' => $quote ? json_encode($quote) : '',
                'extends' => $extends,
                'order_id' => $orderId,
            ];
            return $data;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    public static function isNeedOrderId($fromRoleId, $toRoleId)
    {
        $bool = false;
        if (in_array($fromRoleId, [Consts::DESIGN_LEADER_ID, Consts::DESIGN_ID]) && $toRoleId == Consts::CUSTOMER_ID) {
            $bool = true;
        }
        if (in_array($toRoleId, [Consts::DESIGN_LEADER_ID, Consts::DESIGN_ID]) && $fromRoleId == Consts::CUSTOMER_ID) {
            $bool = true;
        }
        return $bool;
    }

    /**
     * 聊天列表
     * @param $userInfo
     * @param string $search
     * @return array
     * @throws \Exception
     */
    public static function getContactList($userInfo, $search = '')
    {
        try {
            $userId = $userInfo['user_id'];
            $where = [];
            $chatSignArr = GroupUserModel::where('user_id', $userId)->column('chat_sign');
            $where[] = ['chat_sign', 'in', $chatSignArr];
            if ($search) {
                $orderIdArr = OrderModel::where('order_name', 'like', "%$search%")->column('id');
                $where[] = ['order_id', 'in', $orderIdArr];
            }
            $field = 'id,order_id,order_name,chat_sign,avatar,title';
            $list = ChatUserModel::where($where)->field($field)->order('last_time', 'desc')->limit(30)->select()->toArray();

            // 群未读消息
            $chatSignArr = array_column($list, 'chat_sign');
            $groupUserArr = GroupUserModel::whereIn('chat_sign', $chatSignArr)
                ->where('user_id', $userId)
                ->column('unread', 'chat_sign');
            // 群聊总人数
            $groupUserCountList = GroupUserModel::whereIn('chat_sign', $chatSignArr)
                ->field('count(1) as num,chat_sign')
                ->group('chat_sign')
                ->select();
            $groupUserCountArr = [];
            foreach ($groupUserCountList as $value) {
                $groupUserCountArr[$value['chat_sign']] = $value['num'];
            }
            $redisHandler = Cache::store('redis')->handler();
            foreach ($list as &$value) {
                $chatSign = $value['chat_sign'];
                // 最后一条信息
                $redisKey = sprintf(RedisKey::LAST_MESSAGE, $chatSign);
                $lastInfo = $redisHandler->hgetall($redisKey);
//                $lastInfo = MessageModel::where('chat_sign', $chatSign)->order('msg_id', 'desc')->find();
                $content = $lastInfo['last_content'] ?? '';
                $isUndo = $lastInfo['is_undo'] ?? 0;
                if ($lastInfo && $isUndo == 1) {
                    if ($lastInfo['from_user_id'] == $userId) {
                        $content = '您' . $content;
                    } else {
                        $content = $lastInfo['from_user_name'] . $content;
                    }
                }
                $value['msg_id'] = $lastInfo['msg_id'] ?? 0;
                $value['lastContent'] = $content;
                $value['type'] = $lastInfo['type'] ?? '';
                $value['sendTime'] = $lastInfo['last_send_time'] ?? '';
                // 群聊总人数
                $value['group_user_count'] = isset($groupUserCountArr[$chatSign]) ? $groupUserCountArr[$chatSign] : 0;
                // 未读消息
                $value['unread'] = isset($groupUserArr[$chatSign]) ? $groupUserArr[$chatSign] : 0;

                // 如果是客户优先显示群聊名称
                if ($userInfo['role_id'] !== Consts::CUSTOMER_ID || $value['title'] == '') {
                    $value['title'] = $value['order_name'];
                }
                $value['avatar'] = FileService::getFullUrl($value['avatar']);
            }
            return $list;
        } catch (\Exception $exception) {
            throw new \Exception('【' . $exception->getLine() . '】' . $exception->getMessage());
        }
    }
}